<template>
  <div>
    socket is loading...
  </div>
</template>

<script>
import Stomp from 'stompjs'
import { ActiveMQ } from '@/constants/active-mq'
import { getToken } from '@/utils/auth'
import { logout } from '@/api/user'
import { MessageType } from '@/constants/message-type'

export default {
  name: 'stomp-mq',
  data() {
    return {
      client: Stomp.client(ActiveMQ.ConnectionString)
    }
  },
  created() {
    this.connect()
  },
  methods: {
    onConnected: function(frame) {
      console.log('Connected: ' + frame)
      const topic = '/topic/' + ActiveMQ.TopicName + ActiveMQ.MessagePrefix
      this.client.subscribe(topic, this.responseCallback, this.onFailed)
    },
    onFailed: function(frame) {
      console.log('Failed: ' + frame)
    },
    responseCallback: function(frame) {
      console.log('responseCallback msg=>' + frame.body)
      console.log('------')
      const message = JSON.parse(decodeURIComponent(frame.body))
      if (message.MessageType === MessageType.ForceLogout) {
        const id = message.Object.Id
        const user = JSON.parse(sessionStorage.getItem(getToken()))
        if (id === user.id) {
          this.$alert('您好，您被管理员强制下线！', '系统强制下线通知', {
            confirmButtonText: '确定',
            showClose: false,
            callback: action => {
              logout(getToken())
              location.reload(true)
            }
          })
        }
      }
    },
    connect: function() {
      const headers = {
        login: ActiveMQ.UserName,
        passcode: ActiveMQ.Password
      }
      this.client.connect(headers, this.onConnected, this.onFailed)
    }
  }
}
</script>

<style scoped>

</style>
